import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:flutter_smart_heating/common/app.dart';
import 'package:flutter_smart_heating/common/global.dart';
import 'package:flutter_smart_heating/service/auth_service.dart';
import 'package:flutter_smart_heating/ui/ui.dart';
import 'package:get/get.dart';

class UiRightMenuItem {
  Widget? child;
  IconData? icon;
  String text;
  Function()? onTap;
  UiRightMenuItem({this.child, this.icon, this.text = '菜单名称', this.onTap});
}

class UiRightMenuButtonGroup extends StatelessWidget {
  const UiRightMenuButtonGroup({
    super.key,
    this.onTap,
    this.onRefresh,
    this.onCopyLink,
    this.child,
    this.showBackHome = true,
    this.showFeedback = true,
    this.showSetting = true,
    this.showHomeMenu = true,
    this.menus = const [],
  });
  final Function()? onTap;
  final Widget? child;
  final List<UiRightMenuItem> menus;
  final bool showHomeMenu;
  final bool showBackHome;
  final bool showFeedback;
  final bool showSetting;
  final Function()? onRefresh;
  final Function()? onCopyLink;

  Future close(context) async {
    if (Navigator.of(context).canPop()) {
      Navigator.of(context).pop();
    }
    await 0.4.delay();
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      margin: const EdgeInsets.only(right: UiTheme.spacingX),
      height: 30,
      decoration: BoxDecoration(
        color: UiTheme(context)
            .matchColor(Colors.white, UiTheme(context).panelBackground),
        border: Border.all(
          width: 0.15,
          color: UiTheme(context).matchColor(
            Colors.grey,
            Colors.grey.withOpacity(0.5),
          ),
        ),
        borderRadius: BorderRadius.circular(15),
      ),
      child: Row(children: [
        GestureDetector(
          behavior: HitTestBehavior.opaque,
          onTap: () {
            onTap?.call();
            FocusManager.instance.primaryFocus?.unfocus();
            showModalBottomSheet(
              context: context,
              showDragHandle: true,
              backgroundColor: UiTheme(context).bottomSheetBackgroundColor,
              shape: const RoundedRectangleBorder(
                borderRadius: BorderRadius.vertical(
                  top: Radius.circular(UiTheme.boxRadiusX),
                ),
              ),
              builder: (context) => menuView(context),
            );
          },
          child: const CircleAvatar(
            radius: 18,
            backgroundColor: Colors.transparent,
            child: UiIcon(UiIcons.more_dot_wave),
          ),
        ),
        VerticalDivider(
          endIndent: 8,
          indent: 8,
          width: 6,
          thickness: 0.2,
          color: UiTheme(context).matchColor(Colors.grey, Colors.white),
        ),
        GestureDetector(
          behavior: HitTestBehavior.opaque,
          onTap: () {
            Navigator.of(context).popUntil((route) =>
                route.settings.name?.split('?').first ==
                (AuthService.instance.isLogined ? '/' : '/splash'));
          },
          child: const CircleAvatar(
            radius: 18,
            backgroundColor: Colors.transparent,
            child: UiIcon(UiIcons.close_dot_circle_outlined),
          ),
        ),
      ]),
    );
  }

  Widget menuView(context) {
    return Material(
      color: Colors.transparent,
      child: SafeArea(
        bottom: true,
        minimum: const EdgeInsets.only(bottom: 30),
        child: Padding(
          padding: const EdgeInsets.symmetric(horizontal: 5),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            mainAxisSize: MainAxisSize.min,
            children: [
              const SizedBox(height: 10),
              child ?? Container(),
              SizedBox(
                height: 80,
                child: ListView(
                  scrollDirection: Axis.horizontal,
                  children: [
                    for (var item in menus)
                      UiMenuItem(
                        icon: item.icon,
                        text: item.text,
                        onTap: () {
                          close(context);
                          item.onTap?.call();
                        },
                        child: item.child,
                      ),
                    if (showBackHome && AuthService.instance.isLogined)
                      const UiMenuItem(
                        icon: Icons.home,
                        text: '返回首页',
                        onTap: App.backHome,
                      ),
                    if (onRefresh != null)
                      UiMenuItem(
                        icon: Icons.refresh,
                        text: '刷新页面',
                        onTap: () async {
                          await close(context);
                          onRefresh?.call();
                        },
                      ),
                    if (onCopyLink != null)
                      UiMenuItem(
                        icon: Icons.copy,
                        text: '复制链接',
                        onTap: () async {
                          await close(context);
                          onCopyLink?.call();
                        },
                      ),
                    if (showSetting && AuthService.instance.isLogined)
                      UiMenuItem(
                        icon: Icons.settings,
                        text: '通用设置',
                        onTap: () async {
                          await close(context);
                          App.push('/setting');
                        },
                      ),
                    if (showFeedback && AuthService.instance.isLogined)
                      UiMenuItem(
                        icon: Icons.feedback,
                        text: '反馈建议',
                        onTap: () async {
                          await close(context);
                          App.push('/feedback');
                        },
                      ),
                  ],
                ),
              ),
              const UiLineBreak(),
              if (GlobalData.menu.isNotEmpty &&
                  showHomeMenu &&
                  AuthService.instance.isLogined)
                SizedBox(
                  height: 80,
                  child: ListView(
                    scrollDirection: Axis.horizontal,
                    children: List.generate(GlobalData.menu.length, (index) {
                      var item = GlobalData.menu[index];
                      return UiMenuItem(
                        text: item['title'],
                        backgroundColor: Colors.transparent,
                        child: CachedNetworkImage(imageUrl: item['image']),
                        onTap: () async {
                          await close(context);

                          App.push(item['url'], openType: item['target']);
                        },
                      );
                    }),
                  ),
                ),
            ],
          ),
        ),
      ),
    );
  }
}
